package com.example.zsr.akpautoupdatedemo.download;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.example.zsr.akpautoupdatedemo.FileUtils.FileInfo;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;



public class DownloadService extends Service {
    private static final String TAG = "zsr";
    public static final String FILEDIR = Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/downloads";
	public static final int MSG_INIT = 1;
	private FileInfo mfiFileInfo;
	private ProgressDialog progressDialog;
	private DownloadTask mTask;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_INIT:
				mfiFileInfo = (FileInfo) msg.obj;
				
				// 启动下载任务
				mTask = new DownloadTask(DownloadService.this,
						mfiFileInfo);
				mTask.download();
				Log.d("zsr", "Taskstart");
				break;
			}
		};
	};

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String status = intent.getStringExtra("status");
		if (status != null) {
			if (status.equals("STOP")) {
				if(mTask != null){
					mTask.isPause = true;
				}
			}
			if (status.equals("GO")) {
				if(mTask != null){
					Log.d("zsr","gaoxiao");
					mTask.isPause = false;
				}
			}
			
		}
		Log.d(TAG, "onStartCommand: ");
		FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");
		new DownloadThread(fileInfo).start();

		// 如果下载完成则自动安装广播
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.msg.apk_installed");
		filter.addAction("com.msg.apk_install_progress");
		registerReceiver(InstallApkReceiver, filter);
		return super.onStartCommand(intent, flags, startId);
	}

	BroadcastReceiver InstallApkReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			String action = arg1.getAction();
			if (action.equals("com.msg.apk_installed")) {
				Toast.makeText(DownloadService.this,
						"下载成功： " + mfiFileInfo.getFileName(), Toast.LENGTH_SHORT).show();
				Uri uri = Uri.fromFile(new File(FILEDIR,mfiFileInfo.getFileName()));
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(uri, "application/vnd.android.package-archive");
				startActivity(intent);
			}
		}
	};

	class DownloadThread extends Thread {
		FileInfo mFileInfo = null;
		HttpURLConnection con = null;
		RandomAccessFile raf = null;

		public DownloadThread(FileInfo fileInfo) {
			this.mFileInfo = fileInfo;
		}

		@Override
		public void run() {
			try {
				// 设置文件下载
				URL url = new URL(mFileInfo.getApkurl());
				con = (HttpURLConnection) url.openConnection();
				con.setRequestMethod("GET");
				con.setReadTimeout(3000);
				if (con.getResponseCode() == 200) {
					// 获取文件长度
					int length = -1;
					length = con.getContentLength();
					if (length == -1) {
						return;
					}
					Log.d("zsr", "hehe: ");
					File dir = new File(FILEDIR);
					if (!dir.exists()) {
						dir.mkdir();
					}
					// 创建本地文件
					File file = new File(dir, mFileInfo.getFileName());
					// 创建任意写入文件
					raf = new RandomAccessFile(file, "rwd");
					raf.setLength(length);
					// 然后把文件写入 fileinfo
					mFileInfo.setLength(length);

					mHandler.obtainMessage(MSG_INIT, mFileInfo).sendToTarget();

				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					raf.close();
					con.disconnect();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			super.run();
		}
	}

}
